package org.nfIt.interceptor;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.el.parser.Token;
import org.nfIt.entity.system.SysUser;
import org.nfIt.utils.AuthContextUtil;
import org.nfIt.vo.common.Result;
import org.nfIt.vo.common.ResultCodeEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

/**
 * ClossName:LoginAuthInterceptor
 * Pakage:org.nfIt.interceptor
 * Description
 *
 *
 * 登入拦截器
 *
 * @Author L
 * @Create 2024/6/19 16:33
 * @Version 2023.1.3
 */
@Component
public class LoginAuthInterceptor implements HandlerInterceptor {

    //注入redis
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    /**
     * 方法前执行
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //1 获取请求方式//如果请求方式是options预检请求，直接放行
        String method = request.getMethod();
        if("OPTIONS".equals(method)) {      // 如果是跨域预检请求，直接放行
            return true ;
        }
        //2 从请求头获取token
        String token = request.getHeader("token");
        //3 如果token为空，返回错误提示
        if (StrUtil.isBlank(token)){
            //异常消息状态码
            responseNoLoginInfo(response);
            return false;
        }

        //4 如果token不为空，拿着token查询redis
        String redisValue = redisTemplate.opsForValue().get("user:login" + token);
        //5 如果redis查询不到数据，返回错误提示
        if (StrUtil.isEmpty(redisValue)){
            responseNoLoginInfo(response);
            return false;
        }

        //6 如果redis查询到用户信息，把用户信息放到ThreadLocal里面
        AuthContextUtil authContextUtil = new AuthContextUtil();
        //JSON.parseObject 方法通常用于将一个JSON格式的字符串（String）转换为一个Java对象（通常是一个类的实例）
        authContextUtil.set(JSON.parseObject(redisValue, SysUser.class));

        //7 把redis用户信息数据更新过期时间
        redisTemplate.expire("user:login" + token,30, TimeUnit.MINUTES);

        //8 放行
        return true;
    }

    /**
     * 封装好异常消息状态码
     * @param response
     */
    //响应208状态码给前端
    private void responseNoLoginInfo(HttpServletResponse response) {
        //统一格式异常消息
        Result<Object> result = Result.build(null, ResultCodeEnum.LOGIN_AUTH);
        //初始化输出流
        PrintWriter writer = null;
        //设置编码格式
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=utf-8");
        try {
            //获取输出流
            writer = response.getWriter();
            //响应给前端
            writer.print(JSON.toJSONString(result));
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //不等于null,关闭流,等于null,不需要关闭流
            if (writer != null) writer.close();
        }
    }


    /**
     * 所有方法执行完执行
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
        //删除threadLocal中保存的用户数据
        AuthContextUtil.remove();
    }

}
